﻿using CryptLib;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Share;
using System.Text.Json;

namespace AntiCheat.MocServer.Controllers;

[ApiController]
public class HomeController : ControllerBase
{
    private readonly ILogger<HomeController> _logger;
    private readonly AESService _aes;
    private readonly AppParams _appParams;

    public HomeController(ILogger<HomeController> logger, AESService aes, IOptions<AppParams> options)
    {
        _logger = logger;
        _aes = aes;
        _appParams = options.Value;
    }

    [HttpPost("/driver/query")]
    public async Task<IActionResult> Post()
    {
        await Request.ReadFormAsync();

        // 获取表单数据
        var key1 = Request.Form["token"];
        var key2 = Request.Form["reqData"];
        ReqData jsonData = JsonSerializer.Deserialize<ReqData>(key2!)!;

        // 处理数据
        //_logger.LogInformation($"Received key1: {key1}, key2: {key2}");
        //_logger.LogInformation(jsonData.CipherText);

        var result = _aes.Decrypt(jsonData.CipherText, _appParams.Key, _appParams.IV);
        _logger.LogInformation(result);

        //var stmp = "{\"id\":\"3fa85f64-5717-4562-b3fc-2c963f66afa6\",\"idcard\":\"string\",\"realname\":\"string\",\"vendor\":\"string\"}";
        PlainData plainData = JsonSerializer.Deserialize<PlainData>(result.TrimEnd('\0'));

        //var cipherText = _aes.Encrypt(@"{""id"": """+ plainData.Id+@", ""score"":  10}   ", _appParams.Key, _appParams.IV);
        _logger.LogInformation($"{{\"id\": \"{plainData.Id}\", \"score\":  10}}");
        var cipherText = _aes.Encrypt($"{{\"id\": \"{plainData.Id}\", \"score\":  10}}", _appParams.Key, _appParams.IV);

        var signText = _aes.MessageDigestWithSalt(cipherText, _appParams.Salt);

        ResponseData response = new ResponseData
        {
            Reason = "查询成功",
            Token = _appParams.Token,
            Timestamp = jsonData.Timestamp,
            CipherText = cipherText,
            TSLen = jsonData.TsLen,
            SignData = signText,
            ErrorCode = 0
        };

        return Ok(response);
    }
}
